//
//  PopoverTableViewController.m
//  X-Touch2
//
//  Created by shengchao yang on 12-3-15.
//  Copyright (c) 2012年 foxhis. All rights reserved.
//

#import "PopoverTableViewController.h"
#import "Singleton.h"
#import "Common.h"
#import "NSString+Additions.h"

@implementation PopoverTableViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil popoverType:(NSInteger) popoverType
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {        
        popType = popoverType;
        _searchBar = (UISearchBar *)[self.view viewWithTag:TagOfUISearchBar];
        [_searchBar becomeFirstResponder];//自动弹出键盘
        
        if(popType == 1){//远程餐单查询(不实时过滤)
        }else if (popType == 2) {//本地餐单查询
        }else if(popType == 3){//菜品查询
        }else if(popType == 4){//查询套餐明细
        }
        _tableView = (UITableView *)[self.view viewWithTag:TagOfUITableView];
        [_tableView setFrame:CGRectMake(0, _searchBar.frame.size.height, self.view.frame.size.width, 
                                       self.view.frame.size.height-_searchBar.frame.size.height)];
    }
    return self;
}

#pragma mark - tableview datasource
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (popType == 1) {
        return AppSession.remoteMenus.count;
    }else if (popType == 2) {
        return AppSession.myOrderMenus.count;
    }else if(popType == 3 || popType == 4){
        return AppSession.searchPlus.count;
    }
    return 10;
}
//自定义row
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"CellIdentifier";
	UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil){
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
	} 
    if (popType == 1) {//远程餐单查询
        RemoteMenus *rm = (RemoteMenus *)[AppSession.remoteMenus objectAtIndex:indexPath.row];
        cell.textLabel.text = [NSString stringWithFormat:@"%@[%@]",JsonField(rm.rmTableDescripts),rm.rmTableNo];         
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@    %@", rm.rmDate, rm.rmEmpno];;
    }else if (popType == 2) {
        MyOrderMenus *myMenu = (MyOrderMenus *)[AppSession.myOrderMenus objectAtIndex:indexPath.row];
        cell.textLabel.text = [NSString stringWithFormat:@"%@[%@]",JsonField(myMenu.ptDescripts),myMenu.ptTableNo];       
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@-%@",myMenu.peEmpno,myMenu.momDescript];
    }else if(popType == 3 || popType == 4){
        PluPlu *tempPlu = (PluPlu *)[AppSession.searchPlus objectAtIndex:indexPath.row];
        cell.textLabel.text = JsonField(tempPlu.ppDescripts);
        PluPrice *tempPrice = tempPlu.ppPluPrices.count>0?[tempPlu.ppPluPrices objectAtIndex:0]:nil;
        NSString *pluProperty1 = [tempPlu.ppTemp isEqualToString:@"1"] ? [NSString stringWithFormat:@"[%@]",TranslateStr(@"临")] : @"";
        NSString *pluProperty2 = [tempPlu.ppRecommended isEqualToString:@"1"] ? [NSString stringWithFormat:@"[%@]",TranslateStr(@"推")] : @"";
        NSString *pluProperty3 = @"";
        if ([tempPlu.ppType isEqualToString:@"0"]) {
            pluProperty3 = [NSString stringWithFormat:@"[%@]",TranslateStr(@"食")];
        }else if ([tempPlu.ppType isEqualToString:@"1"]) {
            pluProperty3 = [NSString stringWithFormat:@"[%@]",TranslateStr(@"烟")];
        }else if ([tempPlu.ppType isEqualToString:@"2"]) {
            pluProperty3 = [NSString stringWithFormat:@"[%@]",TranslateStr(@"酒")];
        }else if ([tempPlu.ppType isEqualToString:@"3"]) {
            pluProperty3 = [NSString stringWithFormat:@"[%@]",TranslateStr(@"套")];
        }
        
        if (tempPrice != nil) {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@%@  %@",pluProperty1,pluProperty2,pluProperty3,PriceFormatter(tempPrice.price,JsonField(tempPrice.units))];
        }else {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@%@  %@",pluProperty1,pluProperty2,pluProperty3, TranslateStr(@"时价")];
        }
    }
    else {
        cell.textLabel.text = [NSString stringWithFormat:@"00%d",indexPath.row];
    }
    return cell;
}
#pragma mark - tableview datadelegate
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (AppSession.popController.popoverVisible) {
        [AppSession.popController dismissPopoverAnimated:NO];
    }
    if (popType == 1) {//已发送
        if (AppSession.isAnimating) {
            UIAlertView *alert =[[ UIAlertView alloc] initWithTitle:TranslateStr(@"正在查询中...") 
                                                            message:nil
                                                           delegate:nil 
                                                  cancelButtonTitle:TranslateStr(@"返回") 
                                                  otherButtonTitles: nil];
            [alert show];
            [alert release];
            return;
        }
        AppSession.remoteMenuIndex = indexPath.row;
        postN(@"SysMsg_RootView_PopOutRemoteMenuDetail");
    }else if(popType == 2){//未发送
        MyNSLog(@"进入我的点单界面");
        //1. 获得LocalMenu
        MyOrderMenus *myMenu = (MyOrderMenus *)[AppSession.myOrderMenus objectAtIndex:indexPath.row];
        [AppSession getCurrentOrderMenu:myMenu.momLocalMenu];    
        //2. 初始化菜本
        [AppSession initPluMenuByBookCode:myMenu.pbCode];
        //3. 进入我的点单界面
        NSDictionary *infos = [NSDictionary dictionaryWithObjectsAndKeys:@"MenuBookChoose", @"FromNibName", @"MyOrderView",@"ToNibName",nil];
        postNWithInfos(SysMsg_RootView_ControllerChange, self, infos);
    }else if(popType == 3 || popType == 4){//菜品查询 + 套餐明细
        MyNSLog(@"弹出菜品大图模式，同时九宫格滚动到当前页面");
        AppSession.searchIndex = indexPath.row;
        AppSession.fullScreenType = popType; 
        postN(SysMsg_RootView_PopOutPluPlu);//弹出大图模式
    }
}

#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope{
    MyNSLog(@"searchBar index=%d, scope=%@",selectedScope, [[searchBar scopeButtonTitles] objectAtIndex:selectedScope]);
    
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar                       // called when text ends editing(隐藏键盘调用)
{
    MyNSLog(@"searchbar end editing text=%@", searchBar.text);
    if (AppSession.popController.popoverVisible) {
        [AppSession.popController dismissPopoverAnimated:NO];
    }
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText   // called when text changes (including clear)
{
    searchText = Trim(searchText);
    searchText = [searchText replaceFrom:@"'" To:@""];
    searchText = [searchText replaceFrom:@" " To:@""];
    searchText = [searchText replaceFrom:@"#" To:@""];
    searchText = [searchText replaceFrom:@"$" To:@""];
    searchText = [searchText replaceFrom:@"%" To:@""];
    searchText = [searchText replaceFrom:@"," To:@""];
    searchText = [searchText replaceFrom:@"." To:@""];
    searchText = [searchText replaceFrom:@"，" To:@""];
    searchText = [searchText replaceFrom:@"。" To:@""];
    searchText = [searchText replaceFrom:@"?" To:@""];
    searchText = [searchText replaceFrom:@"*" To:@""];
    searchText = [searchText replaceFrom:@"{" To:@""];
    searchText = [searchText replaceFrom:@"}" To:@""];
    searchText = [searchText replaceFrom:@"(" To:@""];
    searchText = [searchText replaceFrom:@")" To:@""];
    searchText = [searchText replaceFrom:@"select" To:@""];
    searchText = [searchText replaceFrom:@"delete" To:@""];
    searchText = [searchText replaceFrom:@"insert" To:@""];
    searchText = [searchText replaceFrom:@"update" To:@""];
    if (popType == 2) {//where 
        MyNSLog(@"实时过滤...searchText=%@",searchText);
        NSString *sql = [NSString stringWithFormat:@"select * from MyOrderMenus where momType='1' and (momLocalMenu like '%%%@%%' or pbCode like '%%%@%%' or ptTableNo like '%%%@%%' or ptDescripts like '%%%@%%' or peEmpno like '%%%@%%') order by momTime asc",searchText,searchText,searchText,searchText,searchText]; 
        [AppSession initMyOrderMenus:sql];//初始化未发送数组
        [_tableView reloadData];
    }else if(popType == 3 || popType == 4){
        NSString *sql = [NSString stringWithFormat:@"select * from PluPlu where pmCode in %@ and (ppHelpCode like '%%%@%%' or ppDescripts like '%%%@%%') order by ppSeqNormal asc",AppSession.currentPmCodes, searchText,searchText,searchText]; 
        [AppSession initSearchPlus:sql];//初始化菜品查询数组 
        MyNSLog(@"searchPlu sql=%@",sql);        
        [_tableView reloadData];
    }else {
        MyNSLog(@"实时过滤功能未定义...");
    }
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar                     // called when keyboard search button pressed
{
    if (AppSession.isAnimating) {
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:TranslateStr(@"正在查询中...") 
                                                        message:nil
                                                       delegate:nil 
                                              cancelButtonTitle:TranslateStr(@"返回") 
                                              otherButtonTitles: nil];
        [alert show];
        [alert release];
        return;
    }
    MyNSLog(@"searchbar doing search");
    if (popType == 1) {
        MyNSLog(@"远程查询");
        NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(startDownload) object:nil];
        [thread start];//启动更新入口
        [thread release];
    }else {
        MyNSLog(@"keyboard search button 没定义...");
    }
}
-(void)startDownload {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    [DataBaseAccess Update:@"delete from RemoteMenus"];//删除本地数据库里的远程主单记录    
    AppSession.isAnimating = YES;
    
    [Common downLoadRemoteMenus:_searchBar.text]; 
    
    [AppSession initRemoteMenus];//初始化远程主单数组
    [_tableView reloadData];//刷新界面
    AppSession.isAnimating = NO;
    [pool release];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar                    // called when cancel button pressed
{
    MyNSLog(@"searchbar canceling...");
    if (AppSession.popController.popoverVisible) {
        [AppSession.popController dismissPopoverAnimated:NO];
    }
}

#pragma mark - View lifecycle
-(void) dealloc{
    MyNSLog(@"PopoverTableViewController is deallocing...");
    [super dealloc];
}
@end
